package com.yunkaweilai.android.fragment;

import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.classic.common.MultipleStatusView;
import com.github.lazylibrary.util.DensityUtil;
import com.github.lazylibrary.util.StringUtils;
import com.google.gson.Gson;
import com.yunkaweilai.android.R;
import com.yunkaweilai.android.activity.lanya.LanyaSetting;
import com.yunkaweilai.android.activity.lanya.StoreInfoActivity;
import com.yunkaweilai.android.activity.login.LoginActivity;
import com.yunkaweilai.android.activity.login.ShiftActivity;
import com.yunkaweilai.android.activity.login.UpdatePassActivity;
import com.yunkaweilai.android.activity.login.ZhuXiaoActivity;
import com.yunkaweilai.android.activity.recharge.RenewalRechargeActivity;
import com.yunkaweilai.android.activity.web.WebActivity;
import com.yunkaweilai.android.base.ActivityCollector;
import com.yunkaweilai.android.base.BaseApplication;
import com.yunkaweilai.android.base.BaseFragment;
import com.yunkaweilai.android.constants.Api;
import com.yunkaweilai.android.interfaces.DialogPayInterface;
import com.yunkaweilai.android.model.AppMyCategoryModel;
import com.yunkaweilai.android.model.home.AppHomeModel;
import com.yunkaweilai.android.model.login.ShiftModel;
import com.yunkaweilai.android.model.login.UserInfoModel;
import com.yunkaweilai.android.net.Glide.GlideUtils;
import com.yunkaweilai.android.net.HttpRequest;
import com.yunkaweilai.android.net.PostProcess;
import com.yunkaweilai.android.utils.Utils;
import com.yunkaweilai.android.view.dialog.MyOutDialog;
import com.yunkaweilai.android.view.home.HeaderBannerView;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.abslistview.ViewHolder;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bingoogolapple.refreshlayout.BGARefreshLayout;


/**
 * 我的界面
 */

public class MyFragment extends BaseFragment implements DialogPayInterface, BGARefreshLayout.BGARefreshLayoutDelegate {


    @BindView(R.id.id_img_head)
    ImageView idImgHead;
    @BindView(R.id.relative_head)
    RelativeLayout rhead;
    @BindView(R.id.id_tv_turnover)
    TextView idTvTurnover;
    @BindView(R.id.id_tv_shift)
    TextView idTvShift;
    @BindView(R.id.id_listview)
    ListView idListview;
    @BindView(R.id.id_listview1)
    ListView idListview1;
    @BindView(R.id.content_view)
    BGARefreshLayout contentView;
    @BindView(R.id.id_multipleStatusView)
    MultipleStatusView idMultipleStatusView;
    @BindView(R.id.id_tv_price_nums)
    TextView idTvPriceNums;
    @BindView(R.id.id_img_shift)
    ImageView idImgShift;
    @BindView(R.id.id_tv_version)
    TextView idTvVersion;
    @BindView(R.id.id_tv_checkout)
    View idTvCheckout;
    @BindView(R.id.my_fragment_view)
    View mView;
    @BindView(R.id.id_tv_name)
    TextView mTextName;
    private HeaderBannerView headerBannerView;
    private AppHomeModel appHomeModel = new AppHomeModel();
    private UserInfoModel.DataBean.StoreEmployeeInfoBean userInfo;
    private ShiftModel shiftModel;
    private String adv = "";
    private String adn = "";
    private CommonAdapter<AppMyCategoryModel.DataBean.ListBean> adapter;
    private CommonAdapter<AppMyCategoryModel.DataBean.ListBean> adapter1;
    private ArrayList<AppMyCategoryModel.DataBean.ListBean> list = new ArrayList<>();

    public void refresh() {
        contentView.beginRefreshing();
//        initHttp();
    }

//    public void allfresh() {
//        contentView.beginRefreshing();
//        initBanner();
//        initHttp();
//
//    }

    @Override
    public int getContentViewId() {
        return R.layout.fragment_my2;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        initRefreshLayout(contentView, this, false);
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        userInfo = BaseApplication.getUserInfo();
        idMultipleStatusView.showLoading();
        idMultipleStatusView.setOnRetryClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                idMultipleStatusView.showLoading();
                initBanner();
                initHttp();
            }
        });
        if (userInfo != null) {
            adv = userInfo.getEmployee_avatar() + "";
            adn = userInfo.getEmployee_name();
            mTextName.setText(adn + "本次收银：");
        }
        idTvShift.setClickable(false);
        idImgShift.setClickable(false);
        PackageInfo pi = null;
        PackageManager pm = getActivity().getPackageManager();
        try {
            pi = pm.getPackageInfo(getActivity().getPackageName(),
                    PackageManager.GET_CONFIGURATIONS);
            idTvVersion.setText("SN:" + pi.versionName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        Utils.MemberHeadImg(mAc, adv, "male", idImgHead);
        initBanner();
        initAdapter();
        initHttp();
    }

    private void initBanner() {
        headerBannerView = new HeaderBannerView(mAc);

        LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams) mView.getLayoutParams(); //取控件当前的布局参数
        linearParams.height = DensityUtil.getDeviceInfo(mAc)[0] * 150 / 600;
        ;// 设置控件的高
        mView.setLayoutParams(linearParams); //使设置好的布局参数应用到控件

        HttpRequest.postUrl(Api.OPERATION_APP_HOME)
                .addParams("is_new", "1")
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        endRefreshOrLoad(true);
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            Gson gson = new Gson();
                            appHomeModel = gson.fromJson(json, AppHomeModel.class);
                            mView.setVisibility(View.GONE);
                            headerBannerView.fillViewForMyFragment(appHomeModel.getData().getLoop_pic(), idListview1);
                            headerBannerView.enqueueBannerLoopMessage();
                            Utils.showPartListView(idListview);
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        endRefreshOrLoad(true);
                    }
                });
    }


    @Override
    public void onStop() {
        super.onStop();
        headerBannerView.removeBannerLoopMessage();
    }

    private void initAdapter() {
        adapter = new CommonAdapter<AppMyCategoryModel.DataBean.ListBean>(mAc, R.layout.item_list_my_item, list) {
            @Override
            protected void convert(ViewHolder viewHolder, final AppMyCategoryModel.DataBean.ListBean item, int position) {
                final String action_type = item.getAction_type();
                final View idLlayoutAll = viewHolder.getView(R.id.id_llayout_all);
                final View view = viewHolder.getView(R.id.id_views);
                switch (action_type) {
                    case "AppUrl":
                    case "AppOld":
                        idLlayoutAll.setVisibility(View.VISIBLE);
                        view.setVisibility(View.GONE);
                        break;
                    case "AppLine":
                        view.setVisibility(View.VISIBLE);
                        idLlayoutAll.setVisibility(View.GONE);
                        break;
                }
                viewHolder.setText(R.id.id_tv_name, item.getApp_category_name() + "");
                idLlayoutAll.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        switch (action_type) {
                            case "AppUrl":
                                WebActivity.actionStart(mAc, item.getJump_url() + "?token=" + BaseApplication.getToken() + "&type_id=" + item.getId());
                                break;
                            case "AppOld":
                                if ("xiugaimima".equals(item.getJump_url())) {
                                    intent2Activity(UpdatePassActivity.class);
                                } else if ("lanya".equals(item.getJump_url())) {
                                    intent2Activity(LanyaSetting.class);
                                } else if ("storeInfo".equals(item.getJump_url())) {
                                    intent2Activity(StoreInfoActivity.class);
//                                    RenewalRechargeActivity.actionStart(mAc,BaseApplication.getToken()+"",true);
                                } else if ("recharge".equals(item.getJump_url())) {
                                    RenewalRechargeActivity.actionStart(mAc, BaseApplication.getToken() + "", true);
                                } else if ("zhuxiao".equals(item.getJump_url())) {
                                    intent2Activity(ZhuXiaoActivity.class);
                                }
                                break;
                        }
                    }
                });
                ImageView idImgIcon = viewHolder.getView(R.id.id_img_icon);

                if (!StringUtils.isEmpty(item.getIcon_url())) {
                    GlideUtils.loadCircleImage(mAc, item.getIcon_url(), idImgIcon, R.mipmap.ic_my_list_icon);
                } else {
                    GlideUtils.loadImage(mAc, R.mipmap.ic_my_list_icon, idImgIcon);
                }
                if (item.getJump_url().equals("zhuxiao")) {
                    GlideUtils.loadImage(mAc, R.mipmap.ic_img_zhuxiao, idImgIcon);
                }

            }
        };
        idListview.setAdapter(adapter);
        adapter1 = new CommonAdapter<AppMyCategoryModel.DataBean.ListBean>(mAc, R.layout.item_list_my_item, list) {
            @Override
            protected void convert(ViewHolder viewHolder, AppMyCategoryModel.DataBean.ListBean item, int position) {
                final View idLlayoutAll = viewHolder.getView(R.id.id_llayout_all);
                final View view = viewHolder.getView(R.id.id_views);
                idLlayoutAll.setVisibility(View.GONE);
                view.setVisibility(View.GONE);
            }
        };
        idListview1.setAdapter(adapter1);

    }

    private void initHttp() {
        HttpRequest.postUrl(Api.SHIFT_INFO)
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {

                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            Gson gson = new Gson();
                            shiftModel = gson.fromJson(json, ShiftModel.class);
                            idTvShift.setClickable(true);
                            idImgShift.setClickable(true);
                            initView();

                        } else {
                            if (idMultipleStatusView != null) {
                                idMultipleStatusView.showError();
                            }
                        }
                        endRefreshOrLoad(true);
                    }

                    @Override
                    public void onError(Exception e) {
                        endRefreshOrLoad(true);
                        if (idMultipleStatusView != null) {
                            idMultipleStatusView.showError();
                        }
                    }
                });
        initAppMyCategory();
    }

    /**
     * 结束刷新组件
     *
     * @param refresh
     */
    private void endRefreshOrLoad(boolean refresh) {
        if (refresh) {
            if (contentView != null) {
                contentView.endRefreshing();
            }
        } else {
            if (contentView != null) {
                contentView.endLoadingMore();
            }
        }
    }

    //获取我的栏目
    private void initAppMyCategory() {
        HttpRequest.postUrl(Api.APP_MY_CATEGORY)
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        endRefreshOrLoad(true);
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            Gson gson = new Gson();
                            AppMyCategoryModel appMyCategoryModel = gson.fromJson(json, AppMyCategoryModel.class);
                            list.clear();
                            AppMyCategoryModel.DataBean.ListBean listBean = new AppMyCategoryModel.DataBean.ListBean();
                            listBean.setAction_type("AppOld");
                            listBean.setApp_category_name("账号注销");
                            listBean.setJump_url("zhuxiao");
                            list.addAll(appMyCategoryModel.getData().getList());
                            if (BaseApplication.getAppRuleModel().isIs_super()) {
                                list.add(listBean);
                            }
                            adapter.notifyDataSetChanged();
                            Utils.showPartListView(idListview);
                            if (idMultipleStatusView != null) {
                                idMultipleStatusView.showContent();
                            }
                        } else {
                            if (idMultipleStatusView != null) {
                                idMultipleStatusView.showError();
                            }
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        if (idMultipleStatusView != null) {
                            idMultipleStatusView.showError();
                        }
                    }
                });
    }

    private void initView() {

        idTvTurnover.setText(shiftModel.getData().getInfo().getStore_turnover_price());
        idTvPriceNums.setText("共" + shiftModel.getData().getInfo().getTotle_order_num() + "笔交易");

    }

    @Override
    public void onResume() {
        super.onResume();
        headerBannerView.enqueueBannerLoopMessage();
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @OnClick({R.id.id_tv_shift, R.id.id_tv_checkout, R.id.id_img_shift})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.id_img_shift:
            case R.id.id_tv_shift:
                BaseApplication.shiftModel = shiftModel;
                intent2Activity(ShiftActivity.class);
                break;
            case R.id.id_tv_checkout:
                MyOutDialog dialog = new MyOutDialog(mAc, this);
                dialog.show();
                break;

        }
    }

    @Override
    public void payMoney() {
        Utils.cleanBaseApplication();
        ActivityCollector.finishAll();
        intent2Activity(LoginActivity.class);

    }

    @Override
    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
//        allfresh();
        idTvTurnover.setText("...");
        idTvPriceNums.setText("共" + "..." + "笔交易");
        initHttp();
    }

    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
        return false;
    }
}
